import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import { cookie } from 'vux'

Vue.use(Router)

// let userInfo = Boolean(cookie.get('userInfo'))
// // this.globalData.cid = cookie.get('userInfo').id
// setTimeout(() => {
//   const userInfo = JSON.parse(cookie.get('userInfo'))
//   if (userInfo) this.a.app.$children[0].globalData.cid = userInfo.id
// }, 500)


const LOGIN_PAGE_NAME = 'registrationLogin'
const PWD_PAGE_NAME = 'reg'
const HOME_PAGE_NAME = 'home'
const GOOD_PAGE_NAME = 'good'
const FORUM_PAGE_NAME = 'forum'
const MY_PAGE_NAME = 'my'

let first = false

const router = new Router({
  routes
})

router.beforeEach((to, from, next) => {
  // 初次进入页面进入首页
  if (!first) {
    first = true
    next({ name: HOME_PAGE_NAME })
  } else {
    // 获取缓存个人信息判断是否登录
    const loginStatus = Boolean(cookie.get('userInfo'))
    if (!loginStatus) {
      // 未登录只能浏览登录、密码、首页、产品、发现、我的等页面
      if (to.name === LOGIN_PAGE_NAME || to.name === PWD_PAGE_NAME || to.name === HOME_PAGE_NAME || to.name === GOOD_PAGE_NAME || to.name === FORUM_PAGE_NAME  ) {
        next()
      } else {
        this.a.app.$vux.toast.show({
          text: '请先登录',
          type: 'cancel'
        })
        this.a.app.$router.push({
          name:'registrationLogin'
        })
      }
    } else {
      next()
    }
  }
})

export default router
